<template>
	<view>
		<!-- 搜索 -->
		<u-navbar class="success_h" zIndex="801" :background="indexHooks.custmStyle()">
			<view style="position: relative;width: 94%;background-color:#f2f2f2;border-radius: 60rpx;">
				<view style="width: 80%;">
					<u-search v-model="params.name" :showAction="false" @blur="getSearch"></u-search>
				</view>
				<view :style="buttonObj" @click="getSearch">
					搜索
				</view>
			</view>

		</u-navbar>

		<!-- 分类菜单 -->
		<view class="bg-white">
			<u-tabs :list="optionsShopList" bar-width='60' :active-item-style="{ color: '#000000' }"
				:bar-style="{ backgroundColor: '#ffc300' }" :gutter='20' :is-scroll="true" v-model="tabActiveName"
				@change="tabsChange"></u-tabs>
		</view>


		<!-- 商品列表 -->
		<view class="list" :style="{ height: `calc(100vh - ${capsuleHeight}px - 44px)` }">
			<view v-if="isListType == 0">
				<scroll-view
					:style="{ height: `calc(100vh - ${capsuleHeight}px - 70px)`, paddingBottom: '180rpx', boxSizing: 'border-box' }"
					scroll-y scroll-with-animation @scrolltolower="isBottomOut" lower-threshold='30'>
					<view v-if="list.length > 0" style="position: relative;" @click.stop="goodClick(item.goodsId)"
						class="item u-flex u-col-top  animate__animated animate__fadeIn " v-for="(item, index) in list"
						:key="index">
						<u-image width="150" height="150" border-radius="12" :src="item.mainImage"></u-image>
						<view class="u-m-l-25 u-flex-1 inner ">
							<view class="u-font-lg fw-middel u-line">{{ item.name }}</view>
							<view class="color-gary-xs u-font-xs u-m-t-6">{{ item.introduce }}</view>
							<view class="u-flex u-m-t-6">
								<u-tag class="u-m-r-12" v-if="item.salePrice != item.price"
									:text="hooksToo.discount(item.salePrice, item.price) + ' 折'" size="mini"
									type="warning"></u-tag>
								<u-tag v-if="item.visitFlag" class="" text="商家上门" size="mini" type="info"></u-tag>
							</view>
							<view class="u-m-t-12 u-flex u-row-between">
								<view class="u-font-sm color-red ">￥<text class="u-font-xl">{{ item.price }}</text>
									<text class="u-m-l-12 color-gary-xs line-del">￥{{ item.salePrice }}</text>
								</view>

								<!-- <u-button v-if="item.variantState==2 || item.goodsType ==2" @click="selectClick(item)"
								type="warning" size="mini">选规格</u-button> -->
								<!-- <u-number-box  @change="addShop($event,item)" v-else-if="item.variantState==1" :index="index"
								 :input-width="80" :disabled-input='true'
								:input-height="30" v-model="item.nums"></u-number-box> -->

							</view>
						</view>

						<view style="align-self:flex-end;" v-if="item.variantState == 2 || item.goodsType == 2">
							<view class="specBtn" @click="selectClick(item)">选规格</view>
						</view>
						<view style="align-self:flex-end;" v-else-if="item.variantState == 1" class="u-flex" @click.stop>
							<view class="operatorBtn" @click="item.nums != 0 ? inputChange('-', item) : ''">-</view>
							<view class="operatorBtn" style="margin: 0 10rpx;">{{ item.nums }}
							</view>
							<view class="operatorBtn" @click="inputChange('+', item)">+</view>
						</view>

					</view>
					<u-empty v-else class="emptyNull" text="暂无数据" mode="search"></u-empty>
				</scroll-view>
			</view>
			<view v-if="isListType == 1" class="shopCommon" style="height:100%">
				<view class="shopLeft" style="height: 100%;overflow-y: auto;">
					<scroll-view scroll-y scroll-with-animation class="u-tab-view menu-scroll-view" :scroll-top="scrollTop"
						id="scroll-el">
						<view v-for="(item, index) in goodsCategoryList" :key="index" class="u-tab-item"
							:class="[current == index ? 'tabActiveClass' : '']" @tap.stop="switchMenu(index)">
							<view v-html="item.name">

							</view>
						</view>
					</scroll-view>
				</view>
				<view class="shopRight" style="height: 100%;overflow-y: auto;">
					<scroll-view style="height: 100%;" :scroll-into-view="selectItemId" :scroll-top="scrollRightTop"
						scroll-y scroll-with-animation @scroll="rightScroll" @touchstart="mainTouch">
						<view v-if="list.length != 0">
							<view class='goodsList' v-for="(item, index) in list" :id="'item' + item.businessClassifyId"
								:key="index + 'a'">
								<view class="typeName" v-html="item.businessClassifyName"></view>
								<view class="goods">
									<view @click.stop="goodClick(child.goodsId)"
										class="item u-flex u-col-top  animate__animated animate__fadeIn "
										style="position: relative;" v-for="(child, indexC) in item.list" :key="indexC">
										<u-image width="150" height="150" border-radius="12"
											:src="child.mainImage"></u-image>

										<view class="u-m-l-25 u-flex-1 inner ">
											<view class="u-font-lg fw-middel u-line">{{ child.name }}</view>
											<view class="color-gary-xs u-font-xs u-m-t-6">{{ child.introduce }}</view>
											<view class="u-flex u-m-t-6">
												<u-tag class="u-m-r-12" v-if="child.salePrice != child.price"
													:text="hooksToo.discount(child.salePrice, child.price) + ' 折'"
													size="mini" type="warning"></u-tag>
												<u-tag v-if="child.visitFlag" class="" text="商家上门" size="mini"
													type="info"></u-tag>
											</view>
											<view class="u-m-t-12 u-flex u-row-between">
												<view class="u-font-sm color-red ">￥<text class="u-font-xl">{{ child.price
												}}</text> <text class="u-m-l-12 color-gary-xs line-del">￥{{
	child.salePrice }}</text>
												</view>
											</view>
										</view>
										<view style="align-self:flex-end;"
											v-if="child.variantState == 2 || child.goodsType == 2">
											<view class="specBtn" @click="selectClick(child)">选规格</view>
										</view>
										<view style="align-self:flex-end;" v-else-if="child.variantState == 1"
											class="u-flex" @click.stop>
											<view class="operatorBtn"
												@click="child.nums != 0 ? inputChange('-', child) : ''">-
											</view>
											<view class="operatorBtn" style="margin: 0 10rpx;">{{ child.nums }}
											</view>
											<view class="operatorBtn" @click="inputChange('+', child)">+</view>
										</view>
									</view>
								</view>
							</view>
						</view>
						<u-empty v-else class="emptyNull" text="暂无数据" mode="search"></u-empty>

					</scroll-view>
				</view>
			</view>
		</view>
	</view>
	<!-- <u-gap height="265"></u-gap> -->
	<shopCart ref="shopCartEl" v-model="show" @shopCarClose='shopCarClose'></shopCart>
</template>

<script setup lang="ts">
import { onLoad, onReachBottom, onReady } from '@dcloudio/uni-app'
import * as indexHooks from '@/hooks/index'
import { computed, reactive, ref, watch, nextTick, getCurrentInstance, } from "vue";

import orderSotre from '@/store/order'
import shopCart from '@/components/shopCart/shopCart.vue'
import orderApi from '@/api/order';
import shopApi from '@/api/shop';
import goodsApi from '@/api/goods';
import * as hooksToo from '@/hooks/tool'
const instance = getCurrentInstance()

const orderPinia = orderSotre()

const ballRef = ref(null)

const shopCartEl = ref(null)

const show = ref(false)

const list = ref([])

let tabActiveName = ref(0)

const buttonObj = reactive({
	position: 'absolute',
	top: '50%',
	transform: 'translateY(-50%)',
	right: '12rpx',
	backgroundColor: '#ffc300',
	color: '#fff',
	border: 'none',
	borderRadius: '30rpx',
	zIndex: 99,
	fontSize: '24rpx',
	width: '84rpx',
	height: '46rpx',
	lineHeight: '46rpx',
	textAlign: 'center'

})

const params = reactive({
	beeperId: orderPinia.orderDetail.beeperId,
	btnType: 1,
	name: "",
	thirdClassifyId: "",
	pageSize: 10,
	pageNo: 1,
	queryType: 1,
	businessVillageIds: '',
	// btnId: orderPinia.orderDetail.btnId,
	// classifyIds: orderPinia.orderDetail.btnServerClassifyIds,
	twoId: '',
	optBusinessId: '',
})

const businessId = ref(0)

const isListType = ref(1)

let businessClassifyIds = ref(0)

let goodsCategoryList = ref([])

let scrollTop = ref(0)

let pageTotal = ref(0)

let scrollRightTop = ref(0)

let selectItemId = ref(0)

let current = ref(0)

let capsuleHeight = ref(0)

let oldScrollTop = ref(0)

let topArr = ref([])

let tipsTop = ref(0)

let isMainScroll = ref(false)

const selectClick = (item) => {
	shopCartEl.value.celectOpen(item)
}

const getSearch = () => {
	list.value = []
	goodsCategoryList.value = []
	businessClassifyIds.value = []
	selectItemId.value = 0
	current.value = 0
	!params.name ? isListType.value = 1 : isListType.value = 0
	!params.name ? getGoodsCategory() : getList('')
}

const minus = (e) => {
	if (e.value == 0) {
		orderPinia.minus(e.index)
	}
}

const add = (e) => {
	if (!ballRef.value) return
	ballRef.value.action(e)
}

const addShop = (e, item) => {
	orderPinia.setShop(item)
}

const optionsBtnidList = ref([])

const getOptionsBtnList = () => {
	return new Promise((reslove, reject) => {
		let list = [
			{
				label: orderPinia.orderDetail.btnName,
				value: orderPinia.orderDetail.btnId
			}, {
				label: "其他",
				value: ''
			}
		]
		reslove(list)

	})
}

const optionsShopList = ref([])

const getShopList = () => {
	let obj = {
		beeperId: orderPinia.orderDetail.beeperId,
		btnType: 1,
		latitude: orderPinia.orderDetail.latitude,
		longitude: orderPinia.orderDetail.longitude,
		provinceNamev: orderPinia.orderDetail.provinceName,
		cityName: orderPinia.orderDetail.cityName,
		areaName: orderPinia.orderDetail.areaName,
		queryType: 1,
		// btnId: orderPinia.orderDetail.btnId,
		special: 1
	}
	return shopApi.getOrderShopList(obj)
}

const goodClick = (id) => {
	// uni.$u.route({
	// 	url: '/pages/order/goods/detail',
	// 	params: {
	// 		id: id
	// 	}
	// })
}



const getList = (type) => {
	isListType.value = 0
	uni.showLoading({
		title: '加载中...',
		mask: true
	})
	switch (type) {
		case 'add':
			break;
		default:
			list.value = []
			params.pageNo = 1
			pageTotal.value = 0
			break;
	}
	goodsApi.beeperBtnId(params).then(res => {
		uni.hideLoading()
		if (res.data.length != 0 && res.data != null) {
			pageTotal.value = res.data.total
			res.data.list.map(item => {
				item.nums = 0
			})
			if (list.value.length < pageTotal.value) {
				list.value = list.value.concat(res.data.list)
				params.pageNo++
			}
			updateListNums()
		} else {
			list.value = []
		}
	})
}

const getClassifyGoodsList = () => {
	uni.showLoading({
		title: '加载中...',
		mask: true
	})
	goodsApi.classifyGoodsList({
		btnType: 1,
		queryType: 1,
		beeperId: orderPinia.orderDetail.beeperId,
		businessId: businessId.value,
		strDate: '',
		businessClassifyIds: businessClassifyIds.value.toString()
	}).then(res => {
		uni.hideLoading()
		if (res.data != null && res.data.length > 0) {
			let datas = res.data as any
			if (goodsCategoryList.value.length == 0) {
				datas = [{ businessClassifyId: 1, businessClassifyName: '其它', list: datas }]
				goodsCategoryList.value = [{ id: 1, name: "其它" }]
			}
			for (let item of datas) {
				item.list.map(item => {
					item.nums = 0
				})
			}
			list.value = datas.map(item => {
				return {
					...item,
					businessClassifyName: item.hasOwnProperty('businessClassifyName') ? item.businessClassifyName.replace(/\<img/gi, '<img style="width:auto;height:17px;vertical-align:-3px"') : '其它'

				}
			})
			updateListNums()
			nextTick(() => {
				getElementTop();
			});
		} else {
			list.value = []
		}

	})
}

const getGoodsCategory = () => {
	shopApi.getGoodsCategory({
		businessId: businessId.value,
		queryType: 1,
		btnType: 1,
		beeperId: orderPinia.orderDetail.beeperId,
		// classifyIds: orderPinia.orderDetail.btnServerClassifyIds,
	}).then(res => {
		if (res.data != null && res.data.length > 0) {
			goodsCategoryList.value = res.data.map(item => {
				return {
					...item,
					name: item.name.replace(/\<img/gi, '<img style="width:auto;height:17px;vertical-align:-3px"')
				}
			})
			businessClassifyIds.value = res.data.map(item => {
				return item.id
			})

		} else {
			goodsCategoryList.value = []
			businessClassifyIds.value = []
			list.value = []
		}
		getClassifyGoodsList()
	})
}

const tabsChange = (index: any) => {
	businessId.value = optionsShopList.value[index].id
	params.optBusinessId = optionsShopList.value[index].id
	list.value = []
	goodsCategoryList.value = []
	businessClassifyIds.value = []
	selectItemId.value = 0
	current.value = 0
	if (isListType.value == 0) {
		getList('')
	} else {
		getGoodsCategory()
	}
}

/* 主区域触摸 */
const mainTouch = () => {
	isMainScroll.value = true;
}

const switchMenu = (index) => {
	selectItemId.value = 'item' + goodsCategoryList.value[index].id
	isMainScroll.value = false;
	current.value = index
}

//获取距离顶部的高度
const getScrollTop = (selector) => {
	return new Promise((resolve, reject) => {
		let query = uni.createSelectorQuery().in(instance);
		query.select(selector + '').boundingClientRect(data => {
			resolve(Math.ceil(data.top) - (capsuleHeight.value + 94))
		}).exec();
	})
}

/* 获取元素顶部信息 */
const getElementTop = async () => {
	/* Promise 对象数组 */
	let p_arr = [];
	/* 遍历数据，创建相应的 Promise 数组数据 */
	for (let i = 0; i < list.value.length; i++) {
		const resu = await getScrollTop(`#item${list.value[i].businessClassifyId}`)
		p_arr.push(resu)
	}
	/* 主区域滚动容器的顶部距离 */
	getScrollTop("#scroll-el").then((res) => {
		let top = res;
		// #ifdef MP-WEIXIN
		top += (Number(capsuleHeight.value) + 44); //主区域滚动容器距离顶部距离
		// #endif
		/* 所有节点信息返回后调用该方法 */
		Promise.all(p_arr).then((data) => {
			tipsTop.value = `${data}upx`;
			topArr.value = data;
		});
	})
}

const rightScroll = (e) => {
	if (!isMainScroll.value) {
		return;
	}
	oldScrollTop.value = e.detail.scrollTop;
	let index = -1;
	if (oldScrollTop.value >= topArr.value[topArr.value.length - 1]) {
		index = topArr.value.length - 1;
	} else {
		index = topArr.value.findIndex((item, index) => {
			return topArr.value[index + 1] >= oldScrollTop.value;
		});
	}
	current.value = (index < 0 ? 0 : index);
}

const updateListNums = () => {
	if (list.value.length == 0) {
		return false
	}
	if (isListType.value == 0) {
		list.value.forEach((itemA) => {
			let matchingItemB = orderPinia.shopList.find((itemB) => itemB.goodsId === itemA.goodsId);
			if (matchingItemB) {
				itemA.nums = matchingItemB.nums;
			}
		});
	} else {
		list.value.forEach((itemA) => {
			// 遍历 itemA 中的 list 数组
			itemA.list.forEach((itemList) => {
				// 查找数组 b 中相同 id 的对象
				let matchingItemB = orderPinia.shopList.find((itemB) => itemB.goodsId === itemList.goodsId);
				if (matchingItemB) {
					// 如果找到匹配的对象，将 b 中的 nums 赋值给 itemA.list 中对应对象的 nums
					itemList.nums = matchingItemB.nums;
				}
			});
		});
	}
}

const isBottomOut = () => {
	if (list.value.length < pageTotal.value) {
		getList('add')
	}
}

const numberChange = (e, item) => {
	orderPinia.setShop(item)
}

const inputChange = (type, item) => {
	switch (type) {
		case '-':
			item.nums--
			break;

		case '+':
			item.nums++
			break;
	}

	orderPinia.setShop(item)
}

const getloadData = () => {
	getOptionsBtnList().then(res => {
		optionsBtnidList.value = res
		return getShopList()
	}).then(res => {
		res.data.map((item, index) => {
			if (index == 0) {
				params.businessVillageIds = item.businessVillageId
				params.optBusinessId = item.id
			}

		})
		optionsShopList.value = res.data as any
		businessId.value = businessId.value===0?optionsShopList.value[0].id:businessId.value
		getGoodsCategory()
	})
}

watch(() => orderPinia.shopList, (New, Old) => {
	if (New.length == 0) {
		if (isListType.value == 0) {
			list.value.map(item => {
				item.nums = 0
			})
		} else {
			for (let item of list.value) {
				item.list.map(item => {
					item.nums = 0
				})
			}
		}
	}
}, { deep: true })

const shopCarClose = (e) => {
	show.value = false
}


onShow(() => {
	getloadData()
})

onReady(() => {
	uni.createSelectorQuery().select('.success_h').boundingClientRect(data => {
		capsuleHeight.value = Math.ceil(data.height)
	}).exec()
})
</script>

<style lang="scss" scoped>
.menuMain {
	display: grid;
	grid-template-columns: 180upx 1fr;
	grid-template-rows: 100%;
	width: 100vw;
	height: 70vh;

	.lf {
		height: 100%;
		background-color: #f1f2f5;

		view {
			line-height: 3em;
			overflow: hidden;
			text-overflow: ellipsis;
			white-space: nowrap;
			padding-left: 22upx;
		}

		view.active {
			background-color: white;
			font-weight: 600;
		}
	}

	.ri {
		height: 100%;
		background-color: #ffffff;
	}

}

.list {
	// height: calc(100vh - );
	padding: 25upx 0 28upx 0;
	box-sizing: border-box;
	overflow-y: auto;

	.item {
		border-radius: 12upx;
		padding: 20upx 18upx;
		box-shadow: 0upx 8upx 16upx rgba(200, 200, 200, .1);
		background-color: white;
		margin-bottom: 25upx;
		box-sizing: border-box;

		.inner {
			min-height: 150upx;
		}
	}
}

.inputstyl {
	width: 60upx;
	text-align: center;
}

.shopCommon {
	display: flex;
}

.shopLeft {
	padding-bottom: 132upx;
	box-sizing: border-box;
	width: 22%;

	.u-tab-view {
		width: 100%;
		height: 100%;
	}

	.u-tab-item {
		height: 110rpx;
		background: #f6f6f6;
		box-sizing: border-box;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 26rpx;
		color: #444;
		font-weight: 400;
		line-height: 1;
	}

	.u-tab-item-active {
		position: relative;
		color: #000;
		font-size: 30rpx;
		font-weight: 600;
		background: #fff;
	}

	.tabActiveClass {
		position: relative;
		color: #000;
		font-size: 28rpx;
		font-weight: 600;
		background: #fff;
	}
}

.shopRight {
	width: 78%;
	margin-left: 20upx;
	padding-bottom: 120upx;
	box-sizing: border-box;

	.typeName {
		height: 60upx;
		font-size: 30upx;
		color: #737475;
	}
}

.specBtn {
	padding: 6rpx 14rpx;
	box-sizing: border-box;
	background-color: #ff9900;
	border-radius: 10rpx;
	font-size: 24rpx;
	color: #fff;
}

.operatorBtn {
	width: 44rpx;
	height: 44rpx;
	line-height: 44rpx;
	font-size: 22rpx;
	background-color: #f2f3f5;
	text-align: center;
}

.emptyNull {
	position: absolute;
	left: 50%;
	top: 50%;
	transform: translate(-50%, -50%);
}</style>